<!DOCTYPE html>
<html>
<body>
<p>This test ensures beforeunload event fires exactly once in a subframe even if the frame was adopted to a frame that appears later in the tree.</p>
<pre id="log"></pre>
<script>

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

function createFrame(id, parent) {
    var iframe = document.createElement('iframe');
    if (parent)
        parent.contentDocument.body.appendChild(iframe);
    else
        document.body.appendChild(iframe);
    iframe.contentDocument.body.appendChild(iframe.contentDocument.createTextNode(id));    
    iframe.contentDocument.body.appendChild(iframe.contentDocument.createElement('br'));
    iframe.contentWindow.onbeforeunload = function () { fired(iframe.contentWindow, id); return null; }
    iframe.style.width = '70%';
    iframe.style.height = '40%';
    return iframe;
}

function log(message) {
    var log = document.getElementById('log');
    log.innerHTML += message + '\n';
}

var expectedOrder = ['parent', 'a', 'adoptee', 'b'];
var i = 0;

function fired(contentWindow, id) {
    if (expectedOrder[i] == id)
        log('PASS: fired on ' + id);
    else
        log('FAIL: fired on ' + id + ' but expected on ' + expectedOrder[i]);
    i++;

    if (contentWindow == adoptee.contentWindow) {
        log('adopting');
        b.contentDocument.body.appendChild(b.contentDocument.adoptNode(adoptee));
        log('adopted');
    }
}

var container = createFrame('parent');
var a = createFrame('a', container);
var adoptee = createFrame('adoptee', a);
var b = createFrame('b', container);

container.onload = function () {
    if (i == expectedOrder.length)
        log('DONE');
    else
        log('Received ' + i + ' events but expected ' + expectedOrder.length);
    if (window.testRunner)
        testRunner.notifyDone();
}
container.src = 'resources/empty.html';

</script>
</body>
</html>
